<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="optcode">
      <el-input v-model="loginForm.optcode" placeholder="请输入用户名">
        <template #prefix>
          <el-icon class="el-input__icon"><user /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon"><lock /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item class="captchaWrap" prop="captcha">
      <el-input
        class="captchaText"
        type="text"
        v-model="loginForm.captcha"
        placeholder="请输入验证码,点击图片刷新验证码"
        style="flex: 1"
      >
      </el-input>
      <el-image class="captchaImg" :src="captchaImg" @click="getCaptchaData"></el-image>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round @click="resetForm(loginFormRef)" size="large">重置</el-button>
    <el-button :icon="UserFilled" round @click="login(loginFormRef)" size="large" type="primary" :loading="loading">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL, VITE_API_URL } from "@/config";
import { convertImageToBase64, getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import JSEncrypt from "jsencrypt";
// import md5 from "js-md5";

const captchaImg = ref("");
const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  optcode: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" }
    // {
    //   //插入正则验证：大小写、数字、至少6位、不常用字符
    //   pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()\-_=+{};:,<.>])[a-zA-Z][a-zA-Z0-9!@#$%^&*()\-_=+{};:,<.>]{5,17}$/,
    //   message: "密码6-18位(以字母开头，同时包含大写字母、小写字母、数字以及?=.*[!@#$%^&*()\-_=+{};:,<.>]特殊字符)",
    //   trigger: "blur"
    // }
  ],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  optcode: "",
  password: "",
  captcha: ""
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;

    loading.value = true;
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(import.meta.env.VITE_PUBLIC_kEY);
    const password = encryptor.encrypt(loginForm.password) as string;
    try {
      // 1.执行登录接口
      const { data } = await loginApi({ ...loginForm, password });
      let { optid, optcode, optname, token, roleids, rightids } = data;
      userStore.setToken(token);
      userStore.setUserInfo({
        userId: optid,
        userName: optname,
        userAccount: optcode
      });
      userStore.setMenuList(rightids);
      userStore.setRoleIdList(roleids);
      // userStore.setFunctionList(rightids);

      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.closeMultipleTab();
      keepAliveStore.setKeepAliveName();

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录",
        type: "success",
        duration: 3000
      });
    } catch (err) {
      getCaptchaData();
      console.log(err);
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const getCaptchaData = async () => {
  try {
    convertImageToBase64(`${VITE_API_URL}/auth/captcha`, (base64Value: string) => {
      captchaImg.value = base64Value;
    });
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
  getCaptchaData();
});
</script>

<style scoped lang="scss">
@import "../index.scss";
.captchaImg {
  cursor: pointer;
}
:deep(.el-input__inner) {
  background-color: rgb(255 255 255 / 0%) !important;
}
:deep(.el-input__inner:-webkit-autofill) {
  transition: background-color 5000s ease-in-out 0s;
}
:deep(.el-input__inner:-webkit-autofill:focus) {
  -webkit-text-fill-color: #333333 !important;
}
</style>
